﻿package core.tool.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import core.tool.bpe.action.ReplaceBean;
import core.tool.bpe.action.ReplaceItemBean;


public class FileHelper {

	public static  String read(String filePath) throws Exception {
		String fileContent = "";
		InputStreamReader ir =new InputStreamReader(new FileInputStream(filePath), "UTF-8");
		BufferedReader br = new BufferedReader(ir);
		String line = br.readLine();
		while (line != null) {
			fileContent += line;
			line = br.readLine();
		}
		ir.close();
		br.close();		
		return fileContent;
	}	
	
	public static void save(String filePath, String fileContent) throws Exception {
		createDir(filePath);
		File modelFile = new File(filePath);
		if (modelFile.exists()) {
			if (!modelFile.delete()) {
				throw new Exception("保存文件异常，文件已存在且无法删除！");
			}
		}
		FileOutputStream fos = new FileOutputStream(modelFile);
		OutputStreamWriter output = new OutputStreamWriter(fos, "UTF-8");
		output.write(fileContent);
		output.close();
	}
	
	private static void createDir(String filePath) throws Exception {
		filePath = filePath.replace("\\", "/");
		filePath = filePath.substring(0, filePath.lastIndexOf("/"));
		File myPath = new File(filePath);
		if (!myPath.exists()) {
			myPath.mkdirs();
		}
	}	
	
	public static void replaceFile(ReplaceBean replaceBean) throws Exception {
		String filePath=replaceBean.getSourceDir();
		System.out.println("替换文件路径："+filePath);
		String fileContent=read(filePath);
		List<ReplaceItemBean> list=replaceBean.getReplaceItems();
		for(ReplaceItemBean replaceItem:list) {
			String before=replaceItem.getBeforeReplace();
			String after=replaceItem.getAfterReplace();
			System.out.println("替换内容："+before+"---->"+after);
			fileContent.replaceAll(before, after);
		}
		save(filePath,fileContent);
	}
	
	
	public static void deleteFile(File file) {
        if (file.exists()) {
	        if (file.isFile()) {
	            file.delete();
	            //System.out.println("删除文件："+file.getAbsolutePath());
	        }else if (file.isDirectory()) {
//	            System.out.println("删除文件："+file.getAbsolutePath());
	            File[] files = file.listFiles();
	            for (int i = 0;i < files.length;i ++) {
	            	deleteFile(files[i]);
	            }
		    file.delete();
	        }
       } else {
           System.out.println("所删除的文件不存在");
       }
    }	
	
	public static int deleteFile(List<String> filePathList) {
		for(String filePath: filePathList) {
			File file=new File(filePath);
			deleteFile(file);
		}
		return 1;
	}
	
	public static int copyFile(Map<String,String> copyFileMap) throws IOException {
		Iterator ite = copyFileMap.entrySet().iterator();
		while(ite.hasNext()){
			Map.Entry<String,String> entry = (Entry) ite.next();
			String key = entry.getKey();
			String value = entry.getValue();
			File fromFile=new File(key);
			File toFile=new File(value);
			if(fromFile.isFile()) {
				copyFile(fromFile,toFile);
			}else if(fromFile.isDirectory()) {
				copyFolder(key,value);
			}
		}
		return 1;
	}
	
    public static void copyFile(File sourceFile, File targetFile) throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            outBuff.flush();
        } finally {
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }

    public static void copyFolder(String sourceDir, String targetDir) throws IOException {
        (new File(targetDir)).mkdirs();
        File[] file = (new File(sourceDir)).listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
                File sourceFile = file[i];
                File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
                copyFile(sourceFile, targetFile);
            }
            if (file[i].isDirectory()) {
                String dir1 = sourceDir + "/" + file[i].getName();
                String dir2 = targetDir + "/" + file[i].getName();
                copyFolder(dir1, dir2);
            }
        }
    }	
	
    public static void main(String[] args) {
    	try {
			copyFile(new File("C:/Users/duankaige/Desktop/系统更新问题.docx"),new File("C:/Users/duankaige/Desktop/系统更新问题1.docx"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
    
	
	
	
	
	
}
